<?php
namespace app\common\library;

use FormManager\Builder;

class Form
{
    /**
     * 输出html结构
     * @param  string $type    生成类型
     * @param  string $name    文本name
     * @param  string $value   文本值
     * @param  array  $options 文本选项（具体参照各类型参数说明）
     * @param  array  $extra   拓展参数
     * @return mixed
     */
    public static function output($type = 'text', $name = '', $value = '', $options = [], $extra = [])
    {
        $value = is_null($value) ? (string) $value: $value;
		$options = is_array($options) ? $options : [];
		$extra   = is_array($extra) ? $extra : [];
    	return method_exists(new Form(), $type) ? self::$type($name, $value, $options, $extra) : false;
    }

    protected static function text($name = '', $value = '', $options = [], $extra = [])
    {
    	return Builder::text()->name($name)->val($value)->attr($extra)->toHtml();
    }

    protected static function number($name = '', $value = '', $options = [], $extra = [])
    {
        return Builder::number()->name($name)->val($value)->attr($extra)->toHtml();
    }

    protected static function email($name = '', $value = '', $options = [], $extra = [])
    {

		return Builder::email()->name($name)->val($value)->attr($extra)->toHtml();
    }

    protected static function color($name = '', $value = '', $options = [], $extra = [])
    {
		return Builder::color()->name($name)->val($value)->attr($extra)->toHtml();
    }

    protected static function hidden($name = '', $value = '', $options = [], $extra = [])
    {
		return Builder::hidden()->name($name)->val($value)->attr($extra)->toHtml();
    }

    protected static function password($name = '', $value = '', $options = [], $extra = [])
    {
		return Builder::password()->name($name)->val($value)->attr($extra)->toHtml();
    }

    protected static function submit($name = '', $value = '', $options = [], $extra = [])
    {
		return Builder::submit()->name($name)->html($value)->attr($extra)->toHtml();
    }

    protected static function week($name = '', $value = '', $options = [], $extra = [])
    {
		return Builder::week()->name($name)->val($value)->attr($extra)->toHtml();
    }

    protected static function textarea($name = '', $value = '', $options = [], $extra = [])
    {
    	return Builder::textarea()->name($name)->val($value)->attr($extra)->toHtml();
    }

    /**
     * 单选按钮
     * @param  string $name    
     * @param  string $value   
     * @param  array  $options 按钮选项(必传，eg：['开启','关闭'])
     * @param  array  $extra   拓展参数
     *                         colspan：每行显示个数(默认不限),
     *                         disabled：禁止点击的（可传数组、字符串，字符串多个用英文逗号分割）
     * @return string
     */
    protected static function radios($name = '', $value = '', $options = [], $extra = [])
    {
	    if(!is_array($options) || empty($options)) return false;

	    // 每行显示多少个
	    if ($extra['colspan']) {
	    	$colspan = max(1, intval($extra['colspan']));
	    	unset($extra['colspan']);
	    }

	    // 禁止点击的
	    if ($extra['disabled']) {
	    	$disabled = (!is_array($extra['disabled']) && !empty($extra['disabled'])) ? ( strpos($extra['disabled'], ',') === false ? $extra['disabled'] : explode(",", $extra['disabled'])) : (array) $extra['disabled'];
	    	unset($extra['disabled']);
	    }

    	$i = 1;
    	$str = '';
        $exists = in_array($value,array_keys($options)) ? true : false;
    	foreach ($options as $k => $v) {
    		$_disabled = (in_array($k, $disabled) || $disabled == 'true') ? 'disabled' : false;
    		$_checked = ($exists == true && $k == $value || $exists == false && $i == 1) ? 'checked' : false;
    		$str .= Builder::radio()->name($name)->checked($_checked)->disabled($_disabled)->val($k)->label($v)->attr($extra).'&nbsp;';
    		if ($colspan > 0 && $i % $colspan == 0) {
    			$str .= '<br/>';
    		}
    		$i++;
    	}

    	return $str;
    }

    /**
     * 复选框
     * @param  string $name    
     * @param  string $value   
     * @param  array  $options 按钮选项(必传，eg：['开启','关闭'])
     * @param  array  $extra   拓展参数
     *                         colspan：每行显示个数(默认不限),
     *                         disabled：禁止点击的（可传数组、字符串，字符串多个用英文逗号分割）
     * @return string
     */
    protected static function checkbox($name = '', $value = '', $options = [], $extra = [])
    {
	    if(!is_array($options) || empty($options)) return false;

	    // 每行显示多少个
	    if ($extra['colspan']) {
	    	$colspan = max(1, intval($extra['colspan']));
	    	unset($extra['colspan']);
	    }

	    // 禁止点击的
	    if ($extra['disabled']) {
	    	$disabled = (!is_array($extra['disabled']) && !empty($extra['disabled'])) ? ( strpos($extra['disabled'], ',') === false ? $extra['disabled'] : explode(",", $extra['disabled'])) : (array) $extra['disabled'];
	    	unset($extra['disabled']);
	    }

    	$i = 1;
    	$str = '';
    	foreach ($options as $k => $v) {
    		$_disabled = (in_array($k, $disabled) || $disabled == 'true') ? 'disabled' : false;
    		$_checked = ($k == $value) ? 'checked' : false;
    		$str .= Builder::checkbox()->name($name.'[]')->checked($_checked)->disabled($_disabled)->val($k)->label($v)->attr($extra).'&nbsp;';
    		if ($colspan > 0 && $i % $colspan == 0) {
    			$str .= '<br/>';
    		}
    		$i++;
    	}
    	return $str;
    }

    /**
     * 下拉框单选
     */
    protected static function select($name = '', $value = '', $options = [], $extra = []) {
    	return Builder::select()->name($name)->options($options)->val($value)->attr($extra);
    }

    /**
     * 上传音乐
     * @param  string $name    
     * @param  string $value   
     * @param  array  $options 上传按钮参数
     *                         id：      上传的html唯一id(默认music，建议传以免id冲突后不可用)
     *                         class：   html的自定义类名称
     *                         url：     上传的url
     *                         mimetype：可上传格式(默认：audio/mpeg,mp3 mpga mpega mp2)
     *                         text：    按钮名称(默认：上传音乐)
     *                         ico：     按钮图标
     * @param  array  $extra   拓展参数
     *                         play：[
     *                             show:  显示试听音乐按钮  true|false
     *                             class：按钮类名
     *                             text:  按钮名称(默认：试听音乐)
     *                             ico:   按钮图标
     *                         ]
     *                         warning: [
     *                             show:  显示警告提示信息  true|false
     *                             title: 提示标题(默认：温馨提示)
     *                             desc:  提示描述
     *                         ]
     * @return string
     */
    protected static function music($name = '', $value = '', $options = [], $extra = [])
    {
        $options['id']       = $options['id'] ? : 'music';
        $options['class']    = $options['class'] ? : 'btn btn-primary';
        $options['mimetype'] = $options['mimetype'] ? : 'audio/mpeg,mp3 mpga mpega mp2';
        $options['text']     = $options['text'] ? : '上传音乐';
        $options['ico']      = $options['ico'] ? : 'fa-upload';

    	$str = '<input type="hidden" name="'. $name .'" value="'. $value .'" id="'. $options['id'] .'" class="form-control" />';
		$str .= '    <button id="plupload-'. $options['id'] .'" class="'. $options['class'] .' plupload" data-input-id="'. $options['id'] .'" data-after-upload="'. $options['id'] .'_up" data-mimetype="'. $options['mimetype'] .'" data-url="'. $options['url'] .'"><i class="fa '. $options['ico'] .'"></i> '. $options['text'] .'</button>';

    	if ($extra['play']['show'] == true)
    	{
            $play_url = $value ? $value : 'javascript:;';
            $extra['play']['class'] = $extra['play']['class'] ? : 'btn btn-primary';
            $extra['play']['text'] = $extra['play']['text'] ? : '试听音乐';
            $extra['play']['ico'] = $extra['play']['ico'] ? : 'fa-play';

    		$str .= '&nbsp;<a href="'. $play_url .'" id="'. $options['id'] .'_play" class="'. $extra['play']['class'] .'" target="_blank"><i class="fa '. $extra['play']['ico'] .'"></i> '. $extra['play']['text'] .'</a>';
    	}

    	if ($extra['warning']['show'] == true)
    	{
    		$extra['warning']['title'] = $extra['warning']['title'] ? : '温馨提示';
    		$extra['warning']['desc'] = $extra['warning']['desc'] ? : '文件格式: mp3,mpeg,mpga,mpega,mp2,文件大小限制：10M';
    		$str .= '<div class="alert alert-warning alert-dismissible" role="alert">
    		              <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
    		              <strong>'. $extra['warning']['title'] .'：</strong>
		                  '. $extra['warning']['desc'] .'
		            </div>';
    	}

        return $str;
    }

    /**
     * 图片上传(含多图)
     * @param  string $name    表单名称
     * @param  string $value   表单值，多个用英文逗号分割
     * @param  array  $options 上传参数设置
     *                         id：上传的html唯一id(默认music，建议传以免id冲突后不可用)
     *                         class：html的自定义类名称
     *                         mimetype：上传格式(默认：image/*)
     *                         multiple：多图上传 true|false (默认false)
     *                         url：上传的url
     *                         text：上传按钮名称
     *                         ico：上传按钮图标
     * @param  array  $extra   拓展参数
     *                         preview：预览,默认不显示 view|popup (view：视图预览，popup：弹窗预览，仅单图上传有效)
     *                         warning: [ 
     *                             show:  显示警告提示信息  true|false
     *                             title: 提示标题(默认：温馨提示)
     *                             desc:  提示描述
     *                         ]
     * 
     * 上传后回调处理(对应js文件)：Upload.api.custom.id_up = function (response) {}
     * @return string html代码
     */
    protected static function image($name = '', $value = '', $options = [], $extra = [])
    {

        $options['id']       = $options['id'] ? : 'imgs';
        $options['class']    = $options['class'] ? : 'btn btn-primary';
        $options['mimetype'] = $options['mimetype'] ? : 'image/*';
        $options['multiple'] = ($options['multiple'] == 'true') ? : 'false';
        $options['text']     = $options['text'] ? : ($options['multiple'] == 'true') ? '上传多图' : '上传图片';
        $options['ico']      = $options['ico'] ? : 'fa-upload';

        $str = '<input type="hidden" id="image-'. $options['id'] .'" name="'. $name .'" value="'. $value .'" />';

        if ($extra['fields_val']) {
            $str .= '<input type="hidden" id="att-ids" name="actives[slide][att_ids]" value="'. $extra['fields_val'] .'" />';
        }

        if ($options['multiple'] == false) {    // TODO::待后台图片裁剪js后再启用
            $str .= '   <button id="plupload-'. $options['id'] .'" class="'. $options['class'] .' plupload" data-input-id="image-'. $options['id'] .'" data-after-upload="'. $options['id'] .'_up" data-mimetype="'. $options['mimetype'] .'" data-preview-id="'. $options['id'] .'" data-multiple="'. $options['multiple'] .'" data-url="'. $options['url'] .'"><i class="fa '. $options['ico'] .'"></i> '. $options['text'] .'</button>';
        }

        if ($extra['warning']['show'] == true) {
            $extra['warning']['title'] = $extra['warning']['title'] ? : '温馨提示';
            $extra['warning']['desc'] = $extra['warning']['desc'] ? : '文件格式: jpeg,png,gif,jpg,文件大小限制：10M';
            $str .= '<style>.alert-warning{margin-top:5px;};</style>';
            $str .= '<div class="alert alert-warning alert-dismissible fc" role="alert">
                        <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                        <strong>'. $extra['warning']['title'] .'：</strong>
                        '. $extra['warning']['desc'] .'
                    </div>';
        }
        
        if ($extra['preview'] == 'view') {  // 视图预览
            $str .= '<style type="text/css">#'. $options['id'] .'{margin-top:5px;} #'. $options['id'] .' li {list-style: none;}</style>';
            $str .= '<div id="'. $options['id'] .'"></div>';
        } elseif ($options['multiple'] == 'false' && $extra['preview'] == 'popup') {  // 弹窗预览（仅限单图）
            $str .= '<a href="javascript:;" style="margin:0px 5px 0px 5px;" id="popup-'. $options['id'] .'" target="_blank" class="btn btn-primary"><i class="fa fa-eye"></i> 预览</a>';

            $str .= '<script type="text/javascript" src="/statics/js/jquery-3.2.1.min.js"></script><script type="text/javascript">';
            $str .= '$("#popup-'. $options['id'] .'").on("click",function(){
                var img_url = $("input[name='. $name .']").val();
                if (img_url == \'\' || img_url == undefined) {
                    Toastr.error("请上传图片!");
                    return false;
                }
                layer.open({
                    title:"图片预览",
                    type: 1,
                    skin: "layui-layer-demo", //样式类名
                    closeBtn: 1, //不显示关闭按钮
                    anim: 2,
                    shadeClose: true, //开启遮罩关闭
                    area: ["500px", "500px"], //宽高
                    content: \'<div style="width:100%;height:100%;text-align:center;"><img src="\'+img_url+\'" style="max-width:500px;max-height:457px;"></div>\'
                });
            })';
            $str .= '</script>';
        }



        return $str;
    }

    /**
     * 图片列表追加上传
     * @param  string $name    表单名称
     * @param  string $value   表单值，多个用数组
     * @param  array  $options 上传选项参数
     *                         id：上传的html唯一id(默认music，建议传以免id冲突后不可用)
     *                         mimetype：上传格式(默认：image/*)
     *                         url：上传的url
     * @param  array  $extra   拓展参数
     *                         warning: [
     *                             show:  显示警告提示信息  true|false
     *                             title: 提示标题(默认：温馨提示)
     *                             desc:  提示描述
     *                         ]
     *
     * 上传后回调处理：Upload.api.custom.id_up = function (response) {}
     * @return string html代码
     */
    protected static function image_list($name = '', $value = '', $options = [], $extra = [])
    {

        $options['id']       = $options['id'] ? : 'cimg';
        $options['mimetype'] = $options['mimetype'] ? : 'image/*';

        $str = '<dl class="fieldlist" data-name="'. $name .'" data-upurl= "'. $options['url'] .'">';

        // 警告信息
        if ($extra['warning']['show'] == true) {
            $extra['warning']['title'] = $extra['warning']['title'] ? : '温馨提示';
            $extra['warning']['desc'] = $extra['warning']['desc'] ? : '文件格式: jpeg,png,gif,jpg,文件大小限制：10M';
            $str .= '<div class="alert alert-warning alert-dismissible" role="alert">
                        <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                        <strong>'. $extra['warning']['title'] .'：</strong> 
                        '. $extra['warning']['desc'] .'
                    </div>';
        }

        $str .= '   <dd><ins>奖品名称</ins></dd>';
        // 赋值
        if ($value && is_array($value)) {
            foreach ($value as $k => $v) {
                $ban_view = '';
                // $ban_view = $v['img'] ? '' : 'disabled';
                $str .= '   <dd class="form-inline" data-key="'. $k .'">
                                <input type="text" name="'. $name .'['. $k .'][name]" class="form-control" data-rule="required" data-msg="奖品名称不能为空" value="'. $v['name'] .'" size="10" />
                                <input type="hidden" data-event="img" name="'. $name .'['. $k .'][img]" id="'. $options['id'] . $k .'" value="'. $v['img'] .'" data-rule="required" data-msg="请上传奖品图片" size="100" />';
                $str .=         '<input type="hidden" id="att-id'. $k .'" name="actives[calculate][prize]['. $k .'][att_id]" value="'. $v['att_id'] .'" />';
                $str .=         '<button id="plupload-'. $options['id'] . $k .'" style="margin:0px 5px 0px 5px;" class="btn btn-primary plupload" data-input-id="'. $options['id'] . $k .'" data-after-upload="'. $options['id'] .'_up" data-mimetype="'. $options['mimetype'] .'" data-url="'. $options['url'] .'"><i class="fa fa-upload"></i> 上传</button>
                                <a href="javascript:;" data-id="popup" style="margin:0px 5px 0px 5px;" target="_blank" class="btn btn-primary '. $ban_view .'"><i class="fa fa-eye"></i> 预览</a>
                                <span class="btn btn-sm btn-danger" data-event="del" title="删除"><i class="fa fa-trash"></i></span>
                            </dd>';
            }
        }

        $str .= '</dl>
            <a href="javascript:;" class="btn btn-sm btn-success" data-event="add"><i class="fa fa-plus"></i> 添加</a>';

        $str .= '<script type="text/javascript" src="/statics/js/jquery-3.2.1.min.js"></script><script type="text/javascript">';

        $str .= '$("[data-event=add]").on("click", function(){
            var key = parseInt($("dl.fieldlist dd:last()").data("key")) + 1;
                key = (isNaN(key) || key == undefined) ? 1 : key;

            var add_html = \'<dd class="form-inline" data-key="\'+ key +\'">\';
                add_html += \'  <input type="text" name="'. $name .'[\'+ key +\'][name]" class="form-control" data-rule="required" data-msg="奖品名称不能为空" value="" size="10" />\';
                add_html += \'  <input type="hidden" data-event="img" name="'. $name .'[\'+ key +\'][img]" class="form-control" id="'. $options['id'] .'\'+ key +\'" value="" data-rule="required" data-msg="请上传奖品图片" size="100" />\';
                add_html += \'  <button id="plupload-'. $options['id'] .'\'+ key +\'" style="margin:0px 5px 0px 5px;" class="btn btn-primary plupload" data-input-id="'. $options['id'] .'\'+ key +\'" data-after-upload="'. $options['id'] .'_up" data-mimetype="'. $options['mimetype'] .'" data-url="'. $options['url'] .'"><i class="fa fa-upload"></i> 上传</button>\';
                add_html += \'  <a href="javascript:;" data-id="popup" style="margin:0px 5px 0px 5px;" target="_blank" class="btn btn-primary "><i class="fa fa-eye"></i> 预览</a><span class="btn btn-sm btn-danger" data-event="del" title="删除"><i class="fa fa-trash"></i></span></dd>\';
            $("dl.fieldlist").append(add_html);
            require(["upload"], function (Upload) {Upload.api.plupload();});
        });';

        $str .= '$(document).on("click","[data-id=popup]",function(){
            var img_url = $(this).parent("dd").find("[data-event=img]").val();
            if (img_url == \'\' || img_url == undefined) {
                Toastr.error("请上传图片!");
                return false;
            }
            layer.open({
                title:"图片预览",
                type: 1,
                skin: "layui-layer-demo", //样式类名
                closeBtn: 1, //不显示关闭按钮
                anim: 2,
                shadeClose: true, //开启遮罩关闭
                area: ["500px", "500px"], //宽高
                content: \'<div style="width:100%;height:100%;text-align:center;"><img src="\'+img_url+\'" style="max-width:500px;max-height:457px;"></div>\'
            });
        });';

        $str .= '$(document).on("click","[data-event=del]", function(){
            $(this).parent("dd").remove();
        });';

        $str .= '</script>';

        return $str;
    }

}